<template>
  <div class="detail-page">
    <div class="breadcrumb">
      <a-breadcrumb>
        <a-breadcrumb-item>
          <a @click="toIndex">首页</a>
        </a-breadcrumb-item>

        <a-breadcrumb-item>
          <a @click="goNext">{{ route.query.from || '历史发布' }}</a>
        </a-breadcrumb-item>
        <a-breadcrumb-item>
          <a>信息详情</a>
        </a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div class="detail">
      <tj-affix ref="affix" :offset-top="affixOffsetTop" :offset-bottom="0" :z-index="98">
        <div class="detail-top">
          <div class="back" @click="goNext">
            <!-- <img src="../../assets/images/icon_back_arrow.png" alt="" /> -->
            <svg-icon class="icon-back-arrow" name="icon_back_arrow" :width="20" :height="20" />
            返回
          </div>
          <div class="btns">
            <a-button type="primary" ghost @click="onDeleteBtnClick"> 删除 </a-button>
            <template v-if="infoState === 0 || infoState === 1 || infoState === 2">
              <a-button type="primary" class="ml-12" ghost @click="onRevocationBtnClick">
                撤回
              </a-button>
              <a-button type="primary" class="ml-12" @click="onInfoEdit"> 编辑 </a-button>
            </template>
            <a-button v-else type="primary" class="ml-12" @click="onInfoRepublish">
              重新发布
            </a-button>
          </div>
        </div>
      </tj-affix>
      <!-- 标题 -->
      <div class="detail-title">
        {{ infoName }}
      </div>
      <!-- 标题下信息区域 -->
      <div class="detail-sub-title">
        <div class="sub-left">
          <span :class="['state', infoStates[infoState]?.className]">
            {{ infoStates[infoState]?.text }}
          </span>
          <span class="ml-16">
            发布有效期：{{ releaseInfoTimingVO.length === 0 ? dayValidTrem : validTrem }}
          </span>
          <!-- 发布频率 -->
          <div class="ml-16">
            频率：
            <span v-if="releaseInfoTimingVO.length === 0">{{ rate }}</span>
            <Popover
              v-else-if="releaseInfoTimingVO.length > 1"
              :get-popup-container="
                triggerNode => {
                  return triggerNode.parentNode || document.body;
                }
              "
              trigger="hover"
            >
              <template #content>
                <div v-for="item in releaseInfoTimingVO" :key="item.id">
                  <span>{{ weekList[item.dayOfWeek] }}</span>
                  <span>
                    （{{ item.timingPartStart.substr(0, 5) }} 至
                    {{ item.timingPartStop.substr(0, 5) }}）
                  </span>
                </div>
              </template>
              {{ rate }}
              {{ releaseFrequency === 1 ? week : '' }}
              （{{ releaseInfoTimingVO[0].timingPartStart.substr(0, 5) }} 至
              {{ releaseInfoTimingVO[0].timingPartStop.substr(0, 5) }}）...
            </Popover>
            <span v-else>
              {{ rate }}
              {{ releaseFrequency === 1 ? week : '' }}
              （{{ timingPartStart }}
              至
              {{ timingPartStop }}）
            </span>
          </div>
        </div>
        <div class="sub-right">
          <span class="ml-16">作者：{{ releaseUserName }}</span>
          <span class="ml-16">{{ getFormattedPublishTime(createTime) }}</span>
        </div>
      </div>
      <!-- 发布描述 -->
      <div v-if="infoType !== 3 && infoDesc" class="detail-content">
        {{ infoDesc }}
      </div>
      <!-- 文章类发布内容 -->
      <div
        v-if="infoType === 3"
        ref="richTextContainerRef"
        class="detail-content rich-text-content"
        v-html="releaseArticleVO.articleContent"
      >
      </div>
      <!-- 图像类发布内容 -->
      <div v-if="infoType === 1" class="detail-content img-list-box">
        <div v-for="(item, index) in infoTypeUrl" :key="index" class="img-item">
          <div class="item-inner" @click="onImagePreview(index)">
            <img v-if="item.type === 'img'" class="img" :src="item.url" />
            <video v-else class="video" :src="item.url"></video>
            <div v-if="item.type === 'video'" class="video-mask">
              <img src="../../assets/images/play-btn.png" alt="" />
            </div>
          </div>
        </div>
      </div>
      <template v-if="infoType === 3">
        <!-- 附件 -->
        <div v-if="releaseArticleVO?.annex?.length > 0" class="module">
          <div class="module-title">附件</div>
          <div class="module-content annex">
            <div v-for="(item, index) in releaseArticleVO.annex" :key="index" class="annex-item">
              <div class="annex-name">
                <i
                  :class="['file-type-icon', `icon_files_${getIconName(item.documentFormat)}`]"
                ></i>
                <!-- <i
                  v-if="['doc', 'docx'].includes(item.documentFormat.toLowerCase())"
                  class="ifont ifont-wid-appendix_icon_word"
                ></i>
                <i
                  v-else-if="item.documentFormat.toLowerCase() === 'pdf'"
                  class="ifont ifont-wid-popup_icon_pdf"
                ></i>
                <i
                  v-else-if="item.documentFormat.toLowerCase() === 'txt'"
                  class="ifont ifont-wid-popup_icon_txt1"
                ></i>
                <i
                  v-else-if="
                    ['png', 'jpeg', 'jpg', 'bmp'].includes(item.documentFormat.toLowerCase())
                  "
                  class="ifont ifont-wid-a-appendix_icon_png2"
                ></i>
                <i
                  v-else-if="['ppt', 'pptx'].includes(item.documentFormat.toLowerCase())"
                  class="ifont ifont-wid-popup_icon_ppt"
                ></i>
                <i
                  v-else-if="['xls', 'xlsx'].includes(item.documentFormat.toLowerCase())"
                  class="ifont ifont-wid-popup_icon_xlsx"
                ></i>
                <i
                  v-else-if="['mp4', 'avi'].includes(item.documentFormat.toLowerCase())"
                  class="ifont ifont-wid-appendix_icon_mp4"
                ></i>
                <i v-else class="ifont ifont-wid-popup_icon_tongyong"></i> -->
                <span>{{ item.documentName }}.{{ item.documentFormat }}</span>
              </div>
              <spam class="download" @click="toTownload(item)">
                <svg-icon name="icon_download" :width="16" :height="16" />
                下载
              </spam>
            </div>
          </div>
        </div>
        <!-- 文章类信息展示封面 -->
        <div class="module">
          <div class="module-title">封面</div>
          <div class="module-content cover">
            <img class="cover-img" :src="thumbnailUrl" alt="" @click="onImagePreview(0)" />
          </div>
        </div>
      </template>
      <!-- 发布位置 -->
      <div class="module">
        <div class="module-title">发布位置</div>
        <div class="module-content location">
          <div class="location-row">
            <div class="location-col th"><span>名称</span></div>
            <div class="location-col th"><span>归属地点</span></div>
            <div class="location-col th"><span>归属班级</span></div>
          </div>
          <div v-for="(item, index) in releaseInfoEquipments" :key="index" class="location-row">
            <div class="location-col">
              <span v-if="item.positionType !== 2" :title="item.equipmentTypeName">
                {{ item.equipmentTypeName }}
              </span>
              <span v-else>泉城e学：通知公告</span>
            </div>
            <div class="location-col">
              <span :title="item.position">{{ item.position || '--' }}</span>
            </div>
            <div class="location-col">
              <span :title="item.className">{{ item.className || '--' }}</span>
            </div>
          </div>
        </div>
      </div>
      <!-- 操作记录 -->
      <div class="module">
        <div class="module-title">操作记录</div>
        <div class="module-content operate">
          <div v-for="(item, index) in releaseOperationLogVO" :key="index" class="operate-item">
            <span>【{{ item.createUserName }}】</span>
            <span>{{ operates[item.oprationType] }}</span>
            <span>{{ item.createTime }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 返回顶部 -->
  <tj-back-top theme="primary" size="small" shape="circle" />
  <!-- 图片视频预览组件 -->
  <image-viewer v-model:visible="previewVisible" v-model:index="curImgIdx" :images="previewImgs" />
  <!-- 富文本图片视频预览组件 -->
  <image-viewer
    v-model:visible="previewRichTextVisible"
    v-model:index="curRichTextImgIdx"
    :images="previewRichTextImgs"
  />
  <!-- 弹框提示 -->
  <my-dialog
    :dialog-state="dialog.visible"
    :dialog-title="dialog.title"
    :dialog-width="dialog.width"
    :icon-type="dialog.warring"
    :show-icon="true"
    :draft-box-visible="false"
    :content-text="dialog.content"
    @handleCancel="dialogCancel"
    @handleOk="dialogOk"
  ></my-dialog>
</template>

<script setup>
import { reactive, ref, computed, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import moment from 'moment';
import { Popover, Message } from 'ant-design-vue';
import { getReleaseInfo } from '@/api/user';
import { deleteReleaseInfo, recallReleaseInfo } from '@/api/post-list.js';
import ImageViewer from '@/components/imageViewer';
import MyDialog from '@/components/dialog';
import { getFormattedPublishTime } from '@/util/formatDate';
import { defaultFengmian, getEscapeUrl } from '@/util/OBSUpload';
import { getFromRouteInfo } from '@/util/utils';

const store = useStore();

// 顶部区域偏移高度
const affixOffsetTop = ref(window.__MICRO_APP_ENVIRONMENT__ ? 70 : 0);
// 图片预览
const previewVisible = ref(false);
const curImgIdx = ref(0);
const previewImgs = computed(() => {
  // 文章类封面预览
  if (infoType.value === 3) {
    return [thumbnailUrl.value];
  }
  // 图像类内容预览
  return infoTypeUrl.value?.map(item => item.url);
});
function onImagePreview(idx) {
  curImgIdx.value = idx;
  previewVisible.value = true;
}
// 富文本图片视频预览
const previewRichTextVisible = ref(false);
const curRichTextImgIdx = ref(0);
const previewRichTextImgs = ref([]);
const richTextContainerRef = ref();
function onBindRichTextPreview(ele) {
  ele.addEventListener('click', e => {
    e.stopPropagation();
    e.preventDefault();
    let curUrl = ele.getElementsByTagName('source')[0]?.src ?? ele.src;
    let idx = previewRichTextImgs.value.findIndex(url => url === curUrl);
    curRichTextImgIdx.value = idx < 0 ? 0 : idx;
    previewRichTextVisible.value = true;
  });
}

function toTownload(item) {
  const download = new XMLHttpRequest();
  download.open('GET', item.documentUrl, true);
  download.responseType = 'blob';
  download.onload = function () {
    const url = window.URL.createObjectURL(download.response);
    const a = document.createElement('a');
    a.href = url;
    a.download = item.documentName + '.' + item.documentFormat;
    a.click();
    // window.$message.success('下载成功');
  };
  download.send();
}

// 发布状态
const infoStates = {
  1: { text: '已发布', className: 'green' },
  2: { text: '待生效', className: 'red' },
  3: { text: '已结束', className: 'gray' },
  4: { text: '已撤回', className: 'red' },
  5: { text: '已删除', className: 'gray' }
};
const weekList = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
const operates = { 1: '发布信息', 2: '删除信息', 3: '编辑信息', 4: '撤回信息' };

// 附件图标
const getIconName = name => {
  name = name.toLowerCase();
  switch (true) {
    case ['png', 'jpg', 'jpeg', 'bmp'].includes(name):
      return 'img';
    case ['doc', 'docx'].includes(name):
      return 'word';
    case ['pdf'].includes(name):
      return 'pdf';
    case ['txt'].includes(name):
      return 'txt';
    case ['ppt', 'pptx'].includes(name):
      return 'ppt';
    case ['xls', 'xlsx'].includes(name):
      return 'xlsx';
    case ['mp4', 'avi'].includes(name):
      return 'mp4';
    default:
      return 'others';
  }
};

// 弹窗相关
const dialog = reactive({
  type: '',
  title: '温馨提示',
  content: '',
  warring: 'warring',
  visible: false,
  width: '330px'
});
// 点击取消
function dialogCancel() {
  dialog.visible = false;
}
// 点击确定
function dialogOk() {
  dialog.visible = false;
  if (dialog.type === 'delete') {
    // 删除信息
    onInfoDelete();
  } else {
    // 撤回信息
    onInfoRevocation();
  }
}
// 顶部删除按钮事件
function onDeleteBtnClick() {
  dialog.content = '是否确认删除该条信息发布？';
  dialog.visible = true;
  dialog.type = 'delete';
}
// 删除信息
function onInfoDelete() {
  let id = route.query.id;
  deleteReleaseInfo([id])
    .then(res => {
      if (res.data.code === 200) {
        Message.success('删除成功');
        // 区分本地和基座内部，封装返回上一页方法
        if (window.__MICRO_APP_ENVIRONMENT__) {
          router.push(getFromRouteInfo());
        } else {
          router.go(-1);
        }
      } else {
        Message.error(res.data.msg);
        return;
      }
    })
    .catch(err => {
      Message.error(err);
    });
}
// 顶部撤回按钮事件
function onRevocationBtnClick() {
  dialog.content = '是否确认撤回该条信息发布？';
  dialog.visible = true;
  dialog.type = 'recall';
}
// 撤回信息
function onInfoRevocation() {
  let id = route.query.id;
  recallReleaseInfo(id)
    .then(res => {
      if (res.data.code === 200) {
        Message.success('撤回成功');
        // 区分本地和基座内部，封装返回上一页方法
        if (window.__MICRO_APP_ENVIRONMENT__) {
          router.push(getFromRouteInfo());
        } else {
          router.go(-1);
        }
      } else {
        Message.error(res.data.msg);
        return;
      }
    })
    .catch(err => {
      Message.error(err);
    });
}
// 顶部编辑按钮事件
function onInfoEdit() {
  let id = route.query.id;
  if (infoType.value === 1) {
    router.push({
      path: '/post-message/imgAndVideo',
      query: {
        id,
        state: '编辑',
        activeState: 0
      }
    });
  } else {
    router.push({
      path: '/post-message/article',
      query: {
        id,
        state: '编辑',
        activeState: 1
      }
    });
  }
}
// 顶部重新发布按钮事件
function onInfoRepublish() {
  let id = route.query.id;
  if (infoType.value === 1) {
    router.push({
      path: '/post-message/imgAndVideo',
      query: {
        id,
        state: '重新发布',
        activeState: 0
      }
    });
  } else {
    router.push({
      path: '/post-message/article',
      query: {
        id,
        state: '重新发布',
        activeState: 1
      }
    });
  }
}

const router = useRouter();
const validPeriodStart = ref('');
const validPeriodStop = ref('');
const releaseFrequency = ref();
const releaseUserName = ref();
const infoDesc = ref();
const createTime = ref();
const infoType = ref();
const infoTypeUrl = ref();
const releaseUserPhone = ref();
const releaseUserDepartment = ref();
const releaseOperationLogVO = ref([]);
const infoName = ref();
const releaseInfoEquipments = ref([]);
const infoState = ref();
const releaseArticleVO = ref({});
const route = useRoute();
const thumbnailUrl = ref();
const isForever = ref('');
let imgDialogUrl = ref(''); // 预览图片地址
let filePage = ref(0); // pdf转换img的数量
let currentPage = ref(1); // pdf转换img的当前页
let pageList = ref([]); // 文档数据
let lookVideoUrl = ref(''); //  s视频详情地址
const releaseInfoTimingVO = ref([]); // 发布频率
let timingPartStart = ref('');
let timingPartStop = ref('');
getReleaseInfo(route.query.id)
  .then(res => {
    let records = res.data.data;
    infoName.value = res.data.data.infoName;
    validPeriodStart.value = moment(res.data.data.validPeriodStart).format('YYYY-MM-DD HH:mm');
    validPeriodStop.value = moment(res.data.data.validPeriodStop).format('YYYY-MM-DD HH:mm');
    releaseFrequency.value = res.data.data.releaseFrequency;
    releaseUserName.value = res.data.data.releaseUserName;
    createTime.value = res.data.data.createTime;
    infoDesc.value = res.data.data.infoDesc;
    isForever.value = res.data.data.isForever;
    infoType.value = res.data.data.infoType;
    releaseInfoTimingVO.value = res.data.data.releaseInfoTimingVO;
    timingPartStart.value =
      res.data.data.releaseInfoTimingVO.length > 0
        ? res.data.data.releaseInfoTimingVO[0].timingPartStart.substr(0, 5)
        : '';
    timingPartStop.value =
      res.data.data.releaseInfoTimingVO.length > 0
        ? res.data.data.releaseInfoTimingVO[0].timingPartStop.substr(0, 5)
        : '';
    if (res.data.data.infoType === 1) {
      //  1图像 2文档 3文章
      let data = [];
      res.data.data.infoImageAndVideoUrlList.forEach(item => {
        data.push({
          type: item.url.substr(item.url.length - 1, 1) !== '4' ? 'img' : 'video',
          url: getEscapeUrl(item.url, 'url')
        });
      });

      infoTypeUrl.value = data;
    }
    if (infoType.value === 0) {
      infoTypeUrl.value = res.data.data.infoTypeUrl;
      lookVideoUrl.value = res.data.data.infoTypeUrl[0];
    }
    releaseUserPhone.value = res.data.data.releaseUserPhone;
    releaseUserDepartment.value = res.data.data.releaseUserDepartment;
    releaseOperationLogVO.value = res.data.data.releaseOperationLogVO;
    releaseInfoEquipments.value = res.data.data.releaseInfoPositions;
    infoState.value = res.data.data.infoState;
    if (infoType.value === 3) {
      let data = [];
      res.data.data.releaseArticleVO.annex.forEach(item => {
        data.push({
          ...item,
          documentUrl: getEscapeUrl(item.documentUrl, 'url')
        });
      });
      releaseArticleVO.value.annex = data;
      if (res.data.data.infoType * 1 === 3) {
        // 文章
        if (defaultFengmian.indexOf(res.data.data.thumbnailUrl) !== -1) {
          thumbnailUrl.value = res.data.data.thumbnailUrl;
        } else {
          thumbnailUrl.value = getEscapeUrl(res.data.data.thumbnailUrl, 'url');
        }
      }
      let articleContent = res.data.data.releaseArticleVO.articleContent;
      // 处理富文本中图片和视频
      previewRichTextImgs.value = getRichTextImgsAndVideos(articleContent);

      releaseArticleVO.value.articleContent = articleContent;
      // 富文本图片视频加点击预览事件
      nextTick(() => {
        const videoEls = richTextContainerRef.value.querySelectorAll('video');
        const imgEls = richTextContainerRef.value.querySelectorAll('img');
        const eleArrs = [...videoEls, ...imgEls];
        eleArrs.forEach(ele => {
          onBindRichTextPreview(ele);
        });
      });
    }
  })
  .catch(err => {
    console.log(err);
  });

// 处理富文本中图片和视频
function getRichTextImgsAndVideos(richTextContent) {
  let data = [];
  // 图片视频
  let imgReg = /(<img|<video|<source).*?(?:>|\/>)/gi;
  // 匹配src属性
  let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
  let arr = richTextContent.match(imgReg);
  // 避免富文本中无src时报错
  if (arr) {
    for (let i = 0; i < arr.length; i++) {
      let src = arr[i].match(srcReg);
      // 获取地址
      if (src && src[1]) {
        data.push(escape2Html(src[1]));
      }
    }
  }
  return data;
}
// 转意符换成普通字符
function escape2Html(str) {
  let arrEntities = { lt: '<', gt: '>', nbsp: ' ', amp: '&', quot: '"' };
  return str.replace(/&(lt|gt|nbsp|amp|quot);/gi, function (all, t) {
    return arrEntities[t];
  });
}

// 频率
const rate = computed(() => {
  if (releaseFrequency.value === 1) {
    return '每周';
  } else {
    return '每天';
  }
});
const week = computed(() => {
  switch (releaseInfoTimingVO.value[0].dayOfWeek) {
    case 1:
      return '周一';
    case 2:
      return '周二';
    case 3:
      return '周三';
    case 4:
      return '周四';
    case 5:
      return '周五';
    case 6:
      return '周六';
    default:
      return '周日';
  }
});
// 有效期限
const validTrem = computed(() => {
  if (isForever.value === 0) {
    return `
      ${moment(validPeriodStart.value).format('YYYY-MM-DD ')}
       至
      ${moment(validPeriodStop.value).format('YYYY-MM-DD')}`;
  } else {
    return `${moment(validPeriodStart.value).format('YYYY-MM-DD ')} 至  永久`;
  }
});
// 立即发布
const dayValidTrem = computed(() => {
  if (isForever.value === 0) {
    return `
      ${moment(validPeriodStart.value).format('YYYY-MM-DD HH:mm ')}
       至
      ${moment(validPeriodStop.value).format('YYYY-MM-DD HH:mm ')}`;
  } else {
    return `${moment(validPeriodStart.value).format('YYYY-MM-DD HH:mm')} 至  永久`;
  }
});
// 分页减
function pageReduce(item) {
  pageList.value.forEach(item => {
    item.state = false;
  });
  currentPage.value = item;
  pageList.value[item - 1].state = true;
}
// 分页加
function pageAdd(item) {
  pageList.value.forEach(item => {
    item.state = false;
  });
  pageList.value[item + 1].state = true;
  currentPage.value = item + 2;
}
const flag = 1;
// 预览视频弹窗
const previewVideoVisible = reactive({
  title: '图像预览',
  default: 'default',
  visible: false,
  width: '823px'
});
// 查看视频详情
function lookVideo() {
  previewVideoVisible.title = '视频预览';
  previewVideoVisible.visible = true;
}
// 查看图片弹窗
const imgDialog = reactive({
  title: '图像预览',
  default: 'default',
  visible: false,
  width: '400px'
});
// 查看图片详情
function lookPhoto(value, type) {
  imgDialogUrl.value = value;
  if (type === 'img') {
    imgDialog.visible = true;
  } else {
    previewVideoVisible.visible = true;
  }
}
function toIndex() {
  router.push({
    path: '/'
  });
}
function goNext() {
  // router.push({
  //   path: '/service/record'
  // });
  // 区分本地和基座内部，封装返回上一页方法
  if (window.__MICRO_APP_ENVIRONMENT__) {
    router.push(getFromRouteInfo());
  } else {
    router.go(-1);
  }
}
</script>
<style lang="less" scoped>
@import './details.less';
</style>
